package com.example.demo.config.schedule;

import com.example.demo.ResBean.constant.RedisConstant;
import com.example.demo.utils.ApplicationContextUtils;
import com.example.demo.utils.RedisUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * 定时任务,定时删除Redis中过期的Token
 *
 * @author 幻
 * @date 2021-05-19 21:34
 */
@Configuration
@EnableScheduling
@Component
public class RedisScheduleTask {
    //间隔7天
    @Scheduled(fixedRate = 7 * 24 * 60 * 60 * 1000L)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        ApplicationContextUtils.getBean("redisUtils");
        Set<String> keys = RedisUtils.keys(RedisConstant.TOKEN_NAME + "*");
        keys.forEach(key -> {
            Set<String> set = RedisUtils.hKeys(key);
            set.forEach(k -> {
                long hget = Long.parseLong(String.valueOf(RedisUtils.hget(key, k)));
                long l = System.currentTimeMillis();
                if (l - hget > 7 * 24 * 60 * 60 * 1000) {
                    RedisUtils.hdel(key, k);
                    System.out.println("成功删除:" + k);
                }
            });
        });

    }

    public static void delToken(String token){
        ApplicationContextUtils.getBean("redisUtils");
        Set<String> keys = RedisUtils.keys(RedisConstant.TOKEN_NAME + token);
        keys.forEach(key -> {
            Set<String> set = RedisUtils.hKeys(key);
            set.forEach(k -> {
                RedisUtils.hdel(key, k);
                System.out.println("成功删除:" + k);

            });
        });
    }
}
